layui.use(["jquery","table","element","layer","form"],function () {
    var $ = layui.jquery;	//声明jquery组件
    var table = layui.table;//声明table组件
    var layer = layui.layer;//声明对话框组件
    var form = layui.form;  //声明表单组件
    var laydate = layui.laydate
    form.render();//更新渲染表单
    var data;
    $.ajaxSettings.async = false;
    $.ajax({
        type: "get",
        url: "/User/getUser",
        success: function (obj) {
            data = obj;
        }
    });
    
    var parks;
    $.ajax({
        type: "get",
        url: "/Manage/getParking",
        success: function (obj) {
            parks = obj;
        }
    });

    //JSON.parse 将一个 JSON 字符串转换为对象
    let newData = JSON.parse(JSON.stringify(data));
    let newparks = JSON.parse(JSON.stringify(parks));	//停车场，动态显示下拉框用

    //数据表格
    var indexTable = table.render({
        elem: "#indexTable",
        //工具栏
        toolbar:"#insert_search",
        autoSort: false,
        page: true,
        cols: [[
        	{field: "userName", title: "门卫",},
            {field: "parkingId", title: "停车场id",},
            {field: "name", title: "停车场名",},

            {field: "action", title: "操作", toolbar: "#actions", width: 200},
        ]],
        data: newData
    });
    
    //头工具栏
    table.on("toolbar(indexTable)",function (obj) {
    	console.info(obj);
    	
    	if(obj.event === 'insert'){
    	  layer.open({
		      type: 1,
		      title: '添加新门卫',
		      maxmin: true,
		      shadeClose: true, //点击遮罩关闭层
		      area : ['360px' , '300px'],
		      content: $('#add-dialog').html(),
		      btn: ['确定','取消'],
		      success: function (layero, index) {
		    	  
		    	  //每次动态从后台读取数据生成下拉框
		    	  $('#parkingName').empty();//清空
		    	  $('#parkingName').append("<option value=' '>请选择</option>");//拼接第一个
		    	 
		    	  $.each(newparks, function (index, item) {
		    		  $('#parkingName').append(new Option(item.name, item.id));// 下拉菜单里添加数据元素
		    	  });
		    	  //需要在页面弹出后重新渲染一下
		    	  form.render('select');
		    	  
	  		    },
		      yes: function(index, layero){	
		    	  //获取数据
		    	let userType = 1;   //用户类型（默认门卫1）
		    	let userName = document.getElementById("userName").value;  	//用户名
		    	let password = document.getElementById("password").value;  	//密码
		    	let parkingId = document.getElementById("parkingName").value;				//停车场id
  		    	
  		    	let datas={'userName':userName,'password':password,'userType':userType,'parkingId':parkingId};
				  $.ajax({
	  			        type: "post",
	  			        url: "/User/insertUser",
	  			        data:datas,
	  			        success: function (obj) { 	
	  			        	layer.alert("添加数据成功")
	  			        	window.location.reload();
	  			        },
				        error:function(){
				        	layer.alert("添加数据失败")
				        }
	  			    });
				  
		      }
		  });
    	}else if(obj.event === 'search'){
    		//查询按钮
    		
    		let str = document.getElementById("searchStr").value;  	//获取输入框数据
    		console.log(str);
    		let datas={'str':str};
    		var searchResult;
    		$.ajax({
			        type: "post",
			        url: "/User/searchUser",
			        data:datas,
			        success: function (obj) { 				        	
			        	
			        	searchResult = obj; //接收后台数据
			     
			        },
			        error:function(){
		        	layer.alert("查询失败")
		        }
			    });
    		let newResult = JSON.parse(JSON.stringify(searchResult));
    		data=newResult;
    		console.log(newResult);
    		table.render({
    	        elem: "#indexTable",
    	        //工具栏
    	        toolbar:"#insert_search",
    	        autoSort: false,
    	        page: true,
    	        cols: [[
    	        	{field: "userName", title: "门卫",},
    	            {field: "parkingId", title: "停车场id",},
    	            {field: "name", title: "停车场名",},

    	            {field: "action", title: "操作", toolbar: "#actions", width: 200},
    	        ]],
    	        data: newResult
    	    });
    	};
    	
    });
    
    //行工具
    table.on("tool(indexTable)",function (obj) {

    	//获取当前行数据
    	let data = obj.data;

    	if(obj.event === 'update'){
    		layer.open({
    			type: 1,
    			title: '修改门卫-停车场',
    			maxmin: true,
    			shadeClose: true, //点击遮罩关闭层
    			area : ['360px' , '300px'],
    			content: $('#update-dialog').html(),
    			btn: ['确定','取消'],
    			success: function (layero, index) {
    				//生成对话框成功后赋值
    				$("#userName").val(obj.data.userName);
    				$("#parkingId").val(obj.data.name);

    				//每次动态从后台读取数据生成下拉框
    				$('#parkingName').empty();//清空
    				$('#parkingName').append("<option value="+ obj.data.parkingId+">"+ obj.data.name+"</option>");//拼接第一个

    				$.each(newparks, function (index, item) {
    					$('#parkingName').append(new Option(item.name, item.id));// 下拉菜单里添加数据元素
    				});
    				//需要在页面弹出后重新渲染一下
    				form.render('select');

    			},
    			yes: function(index, layero){	
    				//获取参数
    				let userName = obj.data.userName;
    				let parkingId=document.getElementById("parkingName").value;

    				let datas={'userName':userName,'parkingId':parkingId};
    				//传递数据
    				$.ajax({
    					type: "post",
    					url: "/User/updateUser",
    					data:datas,
    					success: function (obj) { 
    						layer.alert("修改成功！")
    					}
    				});
    				window.location.reload();
    			}
    		});
    	}else if(obj.event === 'delete'){
    		//核实
    		layer.confirm("确定要删除该用户？",{
    			btn: ['确认', '取消']
    		}, function () {
    			//按钮1事件
    			$.ajax({
    				type: "post",
    				url: "/User/deleteUser",
    				data:{'userName':obj.data.userName},
    				success: function (obj) {
    					layer.alert("删除成功！")
    					window.location.reload();
    				}
    			});
    		}, function(){
    			// 按钮2的事件
    		});
    		
    		
    	}

    });

});